package com.example.tests;

import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.*;
import static com.example.fw.ContactHelper.MODIFICATION;
import org.testng.annotations.Test;

import com.example.fw.WebDriverHelperBase;
import com.example.utils.SortedListOf;

public class ContactModificationTests extends TestBase {
	
	@Test(dataProvider = "randomValidContactGenerator")
	  public void testContactModification(ContactData contact) throws Exception {
	 	// save current list of contacts
//		SortedListOf<ContactData> oldList = new SortedListOf<ContactData>(app.getHibernateHelper().listContacts());
		SortedListOf<ContactData> oldList = app.getModelContacts().getContacts();

	 	int index = app.getContactHelper().getRandomContactIndex(oldList);
	 	
	 	if (index > 0) {
	 		
	 		if (index % 2 == 0) {
	 			// empty fields of contact do not overwrite old values 
				app.getContactHelper().modifyContact(index, contact, WebDriverHelperBase.KEEP);
		    
			 	// save updated list of contacts
//				SortedListOf<ContactData> newList = app.getContactHelper().getUiContacts();
				SortedListOf<ContactData> newList = app.getModelContacts().getContacts();
			 	
//			 	// update oldContact with non-empty fields of contact
//			 	ContactData oldContact = oldList.get(index);
//			 	oldContact.updateContact(contact, MODIFICATION);

			  assertThat(newList, equalTo(oldList));
			} else {
	 			// empty fields of contact overwrite old values 
				app.getContactHelper().modifyContact(index, contact, WebDriverHelperBase.OVERWRITE);
		    
			 	// save updated list of contacts
//				SortedListOf<ContactData> newList = app.getContactHelper().getUiContacts();
				SortedListOf<ContactData> newList = app.getModelContacts().getContacts();
		 	
			  assertThat(newList, equalTo(oldList));
			}
	 		
	    // compare model to implementation
	    if (wantToCheck()) {
	      if ("yes".equals(app.getProperty("check.db"))) {
	        assertThat(app.getModelContacts().getContacts(), equalTo(app.getHibernateHelper().listContacts()));
	        System.out.println("DB check done. On contact: " + contact.getFirstName());
	      }
	      
	      if ("yes".equals(app.getProperty("check.ui"))) {
	        assertThat(app.getModelContacts().getContacts(), equalTo(app.getContactHelper().getUiContacts()));
	        System.out.println("UI check done. On contact: " + contact.getFirstName());
	      }
	    }
	 	}
    
	  }

}
